package router

import (
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/accesslog"
	"github.com/kataras/iris/v12/x/errors"
	"github.com/sirupsen/logrus"
	"io"
	"os"

	"github.com/kataras/iris/v12/middleware/cors"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"

	// "github.com/iris-contrib/middleware/cors"
	"github.com/iris-contrib/middleware/csrf"
)

func InitMiddleware(app *iris.Application) {
	Csrf(app)
	Cors(app)
	LogAccess(app)
	LogError(app)

	app.Use(recover.New())
}
func Csrf(app *iris.Application) {
	secret := "secret"
	csrfMiddleware := csrf.Protect([]byte(secret), csrf.CookieName("csrf_token"))
	app.Use(csrfMiddleware)
}
func Cors(app *iris.Application) {
	app.UseRouter(cors.New().
		HandleErrorFunc(func(ctx iris.Context, err error) {
			fmt.Println("cors err: ", err)
			errors.FailedPrecondition.Err(ctx, err)
		}).
		// ExtractOriginFunc(cors.StrictOriginExtractor).
		// ReferrerPolicy(cors.NoReferrerWhenDowngrade).
		// AllowOrigin("localhost:9403,localhost:9405,media.beesoft.ink,media.kaikai.vip").
		Handler())
	// AllowedOrigins:   []string{"http://localhost:9405", "http://media.beesoft.ink", "http://media.kaikai.vip"},
	// AllowCredentials: true,
	// AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
	// AllowedHeaders:   []string{"Content-Type", "Authorization"},
}
func LogAccess(app *iris.Application) {
	requestLogger := logger.New(logger.Config{
		Status:             true,
		IP:                 true,
		Method:             true,
		Path:               true,
		Query:              true,
		MessageContextKeys: []string{"logger_message"},
		MessageHeaderKeys:  []string{"User-Agent"},
	})
	app.Use(requestLogger)
}
func LogError(app *iris.Application) {
	logger := logrus.New()
	logger.SetFormatter(&logrus.JSONFormatter{})
	logger.SetOutput(os.Stdout) // Log to stdout, or specify a file

	app.Use(func(ctx iris.Context) {
		logger.WithFields(logrus.Fields{
			"method": ctx.Method(),
			"path":   ctx.Path(),
			"ip":     ctx.RemoteAddr(),
		}).Info("Incoming request")

		ctx.Next()

		logger.WithFields(logrus.Fields{
			"status": ctx.GetStatusCode(),
		}).Info("Response sent")
	})

}
func LogAccess2() {
	file, err := os.Create("../storage/logger/access.logger")
	if err != nil {
		fmt.Println("Error creating file:", err)
		return
	}
	defer func(file *os.File) {
		err := file.Close()
		if err != nil {
			panic(err)
		}
	}(file)
	accesslog.New(io.MultiWriter(file, os.Stdout))
}
